package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author songyi
 * @date 2020/7/1 0001 2:31
 * @description 文件类加载器
 */
public class FileClassLoader extends ClassLoader {

    // 类路径
    private String servletClassPath;

    public String getServletClassPath() {
        return servletClassPath;
    }

    public void setServletClassPath(String servletClassPath) {
        this.servletClassPath = servletClassPath;
    }

    public FileClassLoader(String servletClassPath) {
        this.servletClassPath = servletClassPath;
    }

    /**
     * 传入自定义servlet类名称，获得Class对象
     * @param servletClass 类名称
     * @return
     * @throws IOException
     */
    public Class getBytesFromFile(String servletClass) throws IOException {
        File file = new File(servletClassPath + servletClass.replaceAll("\\.", "/") + ".class");
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[2048];
        int len = 0;
        int ch;
        while ((ch = fis.read(data)) != -1) {
            len = ch;
        }
        return defineClass(servletClass, data, 0, len);
    }
}
